package com.seuic.hnapps.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class CommAdapter {
	private String address = "127.0.0.1"; //

	private int commport = 3551; // 

	private int timeout = 10000; // 

	private int maxbytes = 10240;
	
	private int msglen = 4;
	
	public CommAdapter(){
		
	}
	
	public void setHeadlen(int hlen){
		this.msglen=hlen;
	}
	
	public CommAdapter(String ip, int port){
		this.address = ip;
		this.commport = port;
	}
	
	public byte[] doComm(byte[] request) {

		Socket client = null;
		byte[] buff = request; // 
		byte[] out = null; // 
		OutputStream os = null;
		InputStream is= null;
		try {
			//address = "127.0.0.1";
			client = new Socket(address, commport);
			os = client.getOutputStream();
			is = client.getInputStream();
			client.setSoTimeout(timeout);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			try {
				os.close();
				is.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}


		try {
			writeMsg(os,buff);
			out = readMsg(is);
			//out = readMsg2(is);
			os.close();
			is.close();
		
		} catch (UnknownHostException e) {

		} catch (IOException e) {
		}
		finally
		{
			try
			{
			client.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return out;
	}

	private byte[] readMsg(InputStream in) {
		byte[] content = null;
	// 
	try {
		byte[] len = new byte[msglen];
		in.read(len);
	//	System.out.println("recv_head=["+new String(len)+"]");
		int bodyLen = Integer.parseInt(new String(len).trim());
		content = new byte[bodyLen];
		int index = 0;
		int offset = 0;
		while (bodyLen - index > 0) {
			index += in.read(content, offset, bodyLen - index);
			offset = index;
		}
	//	System.out.println("recv_buff=["+new String(content)+"]");
	} catch (SocketTimeoutException e) {

	} catch (IOException e) {

	}
		return content;
	}
	
	private byte[] readMsg2(InputStream in) {
		byte[] content = new byte[maxbytes];;
		try {
			in.read(content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	//	System.out.println("recv_buff=["+new String(content)+"]");
		return content;
	}
	
	private void writeMsg(OutputStream out, byte[] req) {
	// 
	try {
		int len = req.length;
		String lens = String.valueOf(len);
		for (; lens.length() < msglen;) {
			lens = "0" + lens;
		}
//		System.out.println("send_head=["+lens+"]");
		byte[] length = new byte[msglen];
		byte[] send = new byte[len + msglen];
		length = lens.getBytes();
		System.arraycopy(length, 0, send, 0, msglen);
		System.arraycopy(req, 0, send, msglen, len);
//		System.out.println("sendbuff=["+new String(send)+"]");
		out.write(send);
		out.flush();
	} catch (IOException e) {
		}
	}
}
